<template>
  <!-- 修改及新增规则 -->
  <div class="modal fade  bs-example-modal-lg"
       id="editRuleModal"
       tabindex="-1"
       role="dialog"
       aria-labelledby="exampleModalLabel"
       @click="agentshow=false">
    <div class="modal-dialog"
         role="document">
      <div class="modal-content"
           style="width: 600px">
        <div class="modal-header">
          <button type="button"
                  class="close"
                  data-dismiss="modal"
                  aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title"
              id="exampleModalLabel">设置佣金规则</h4>
        </div>
        <div class="modal-body form-horizontal">
          <div class="row form-group">
            <font color="#FF0000">（注意：若楼盘设置了佣金规则，所有报备产生的佣金将自动按佣金规则计算生成，不支持手动编辑佣金；若需要手动编辑调整合作机构佣金，则不用设置佣金规则）</font>
          </div>
          <div class="row form-group">
            <div class="col-md-6">
              <label class="col-md-3 label-header control-label">楼盘</label>
              <div class="col-md-9">
                <input type="text"
                       class="layui-input"
                       v-model="parent.premisesName" />
              </div>
            </div>
            <div class="col-md-6">
              <label class="col-md-3 label-header control-label">佣金状态</label>
              <div class="col-md-9">
                <select name="quiz1"
                        class="layui-input"
                        id="state"
                        v-model="state">
                  <option value="1"
                          selected="">有效</option>
                  <option value="0">失效</option>
                </select>
              </div>
            </div>
          </div>
          <div class="row form-group"
               style="margin-top: 10px">
            <div class="col-md-6">
              <label class="col-md-3 label-header control-label">合作机构</label>
              <div class="col-md-9"
                   style="position: relative">
                <input type="text"
                       class="layui-input"
                       v-model="parent.companyName" />
              </div>
            </div>
            <div class="col-md-6"
                 v-show="lostTimeState">
              <label class="col-md-3 label-header control-label">失效时间</label>
              <div class="col-md-9">
                <input class="layui-input"
                       name="losttime"
                       id="losttime" />
              </div>
            </div>
          </div>
          <div class="row">
            <ul class="nav nav-tabs">
              <li id="nav-fixed"
                  class="col-md-6"
                  v-bind:class="{ active: selectType }"><a data-toggle="tab"
                   @click="modelShow('#tab-fixed')">按固定</a></li>
              <li id="nav-labber"
                  class="col-md-6"
                  v-bind:class="{ active: !selectType }"><a data-toggle="tab"
                   @click="modelShow('#tab-labber')">按阶梯</a></li>
            </ul>

          </div>
          <div>
            <!-- 按固定 start -->
            <div v-show="selectType">
              <fieldset class="layui-elem-field layui-field-title"
                        style="margin-bottom: 5px;">
                <legend style="font-size:16px;border:none;width: auto">*选择佣金类型</legend>
              </fieldset>
              <div class="row">
                <label class="col-xs-12">分销佣金=成交总价（元）*N%（N%为佣金比例）</label>
                <label class="col-xs-12">备注：填写的数值均为包含关系</label>
              </div>
              <div class="row"
                   style="line-height: 38px;">
                <div class="col-xs-3"
                     style="text-align: right">
                  <label>
                    <input type="radio"
                           name="commission-type-radio"
                           v-model="commissionType"
                           value="1">
                    佣金金额
                  </label>
                </div>
                <div class="col-xs-6">
                  <input type="number"
                         name="commission-sum-value"
                         class="layui-input"
                         placeholder="请输入佣金金额"
                         v-model="amount"
                         v-on:input="amount = checkNum2Point(amount,10)"
                         ref="amount" />
                </div>
                <label style="text-align: left"
                       class="col-xs-3">元</label>
              </div>
              <div class="row"
                   style="line-height: 38px;">
                <div class="col-xs-3"
                     style="text-align: right">
                  <label>
                    <input type="radio"
                           name="commission-type-radio"
                           v-model="commissionType"
                           value="2">
                    佣金比例
                  </label>
                </div>
                <div class="col-xs-6">
                  <input type="number"
                         name="commission-radio-value"
                         class="layui-input"
                         placeholder="请输入佣金比例"
                         v-model="rate"
                         v-on:input="rate = checkNum2Point(e,rate,5)" />
                </div>
                <label style="text-align: left"
                       class="col-xs-3">%</label>
              </div>
              <fieldset class="layui-elem-field layui-field-title"
                        style="margin-bottom: 5px;">
                <legend style="font-size:16px;border:none;width: auto">*选择结算周期</legend>
              </fieldset>
              <!--  固定结算周期 -->
              <div class="row"
                   style="margin: 0 auto">
                <ul style="line-height: 38px;">
                  <li class="col-xs-2 text-center"><label><input type="radio"
                             name="fixed-settlement-cycle"
                             value="1"
                             v-model="settlementCycle"
                             title="日结算"> 日结算</label></li>
                  <li class="col-xs-2 text-center"><label><input type="radio"
                             name="fixed-settlement-cycle"
                             value="7"
                             v-model="settlementCycle"
                             title="周结算"> 周结算</label></li>
                  <li class="col-xs-3 text-center"><label><input type="radio"
                             name="fixed-settlement-cycle"
                             value="15"
                             v-model="settlementCycle"
                             title="半月结算"> 半月结算</label></li>
                  <li class="col-xs-2 text-center"><label><input type="radio"
                             name="fixed-settlement-cycle"
                             value="30"
                             v-model="settlementCycle"
                             title="月结算"> 月结算</label></li>
                  <li class="col-xs-3 text-center"><label><input type="radio"
                             name="fixed-settlement-cycle"
                             value="90"
                             v-model="settlementCycle"
                             title="季度结算"> 季度结算</label></li>
                </ul>
                <ul>
                  <li class="col-xs-2 text-center">(T+1)</li>
                  <li class="col-xs-2 text-center">(T+7)</li>
                  <li class="col-xs-3 text-center">(T+15)</li>
                  <li class="col-xs-2 text-center">(T+30)</li>
                  <li class="col-xs-3 text-center">(T+90)</li>
                </ul>
              </div>
              <!--  固定结算周期 -->
            </div>
            <!-- 按固定 end -->
            <!-- 按阶梯 start -->
            <div v-show="!selectType"
                 style="margin: 0px 30px">
              <div class="row">
                <div class="col-xs-6 text-center">
                  <label>
                    <input type="radio"
                           name="ladder"
                           lay-filter="unit"
                           title="按成交套数"
                           value="3"
                           v-model="commissionType">
                    按成交套数
                  </label>
                </div>
                <div class="col-xs-6 text-center">
                  <label>
                    <input type="radio"
                           name="ladder"
                           lay-filter="unit"
                           title="按成交总额"
                           value="4"
                           v-model="commissionType">
                    按成交总额
                  </label>
                </div>
              </div>
              <div class="info"
                   style="color:#5454ea;margin: 5px auto">
                <label class="lable-mid layui-col-xs12">例如：</label>
                <label class="lable-mid layui-col-xs12">成交10套以下，佣金比例为1.8%；成交11-20套，佣金比例为2%；成交21套以上，佣金比例为3%；</label>
                <label class="lable-mid layui-col-xs12">备注：填写的数值均为包含关系</label>
              </div>
              <!-- 阶梯1 start-->
              <div class="row"
                   style="line-height: 38px;">
                <label class="lable-middle col-none col-xs-2 deal-type-lable-1">成交{{unitTitle}}</label>
                <div class="col-xs-3 col-none">
                  <input type="number"
                         class="layui-input"
                         v-model="end1"
                         v-on:input="end1 = checkNum2Point(end1,commissionType == 3?5:10)" />
                </div>
                <label class="lable-middle col-none col-xs-4 deal-type-lable-2"><span class="unit">{{unit}}</span>以下，佣金比例为</label>
                <div class="col-xs-2 col-none">
                  <input type="number"
                         class="layui-input"
                         v-model="rule1"
                         v-on:input="rule1 = checkNum2Point(rule1,5)" />
                </div>
                <label class="lable-middle col-none col-xs-1"
                       style="text-align: left">%</label>
              </div>
              <!-- 阶梯1 end-->
              <!-- 阶梯2 start-->
              <div class="row"
                   style="margin-top: 5px;margin-bottom: 5px;line-height: 38px;">
                <label class="lable-middle col-none col-xs-2 deal-type-lable-1">成交{{unitTitle}}</label>
                <div class="col-xs-2 col-none">
                  <input type="number"
                         class="layui-input"
                         v-model="start2"
                         v-on:input="start2 = checkNum2Point(start2,commissionType == 3?5:10)">
                </div>
                <label class="lable-middle col-none col-xs-1">-</label>
                <div class="col-xs-2 col-none">
                  <input type="number"
                         class="layui-input"
                         v-model="end2"
                         v-on:input="end2 = checkNum2Point(end2,commissionType == 3?5:10)">
                </div>
                <label class="lable-middle col-none col-xs-2 deal-type-lable-1"><span class="unit">{{unit}}</span>佣金比例为</label>
                <div class="col-xs-2 col-none">
                  <input type="number"
                         class="layui-input"
                         v-model="rule2"
                         v-on:input="rule2 = checkNum2Point(rule2,5)" />
                </div>
                <label class="lable-middle col-none col-xs-1"
                       style="text-align: left">%</label>
              </div>
              <!-- 阶梯2 end-->
              <!-- 阶梯3 start -->
              <div class="row"
                   style="line-height: 38px;">
                <label class="lable-middle col-none col-xs-2 deal-type-lable-1">成交{{unitTitle}}</label>
                <div class="col-xs-3 col-none">
                  <input type="number"
                         class="layui-input"
                         v-model="start3"
                         v-on:input="start3 = checkNum2Point(start3,commissionType == 3?5:10)" />
                </div>
                <label class="lable-middle col-none col-xs-4 deal-type-lable-2"><span class="unit">{{unit}}</span>以上，佣金比例为</label>
                <div class="col-xs-2 col-none">
                  <input type="number"
                         class="layui-input"
                         v-model="rule3"
                         v-on:input="rule3 = checkNum2Point(rule3,5)" />
                </div>
                <label class="lable-middle col-none col-xs-1"
                       style="text-align: left">%</label>
              </div>
              <!-- 阶梯3 end-->
              <fieldset class="layui-elem-field layui-field-title"
                        style="margin-bottom: 5px">
                <legend style="font-size:16px;border:none;width: auto">*选择佣金结算周期</legend>
              </fieldset>
              <!-- 结算周期 start-->
              <div class="row">
                <div class="layui-input-block">
                  <label>
                    <input type="radio"
                           name="ladder-settlement-cycle"
                           value="30"
                           title="月结算(默认为每月的10号)"
                           checked=""
                           v-model="commission.settlementCycle">
                    月结算(默认为每月的10号)
                  </label>
                </div>
                <div class="layui-input-block">
                  <label>
                    <input type="radio"
                           name="ladder-settlement-cycle"
                           value="90"
                           title="季度结算(默认为下一季度第一个月的10号)"
                           checked=""
                           v-model="commission.settlementCycle">
                    季度结算(默认为下一季度第一个月的10号)
                  </label>
                </div>
              </div>
              <!-- 结算周期 end -->
            </div>
            <!-- 按阶梯 end -->
          </div>

          <div class="row"
               style="margin: 15px 15px  0 15px;border-top:1px solid #ccc">
            <label style="float:left;line-height: 38px;">生效日期</label>
            <div class="col-xs-4"
                 style="margin-top: 5px">
              <input name="effecttime"
                     id="effecttime1"
                     class="form-control" />
            </div>
          </div>

        </div>
        <div class="modal-footer">
          <button type="button"
                  class="btn btn-primary"
                  @click="editRule"
                  :disabled="isShow">确定</button>
          <button type="button"
                  class="btn btn-default"
                  data-dismiss="modal">取消</button>
        </div>
      </div>
    </div>
  </div>
  <!--修改及新增规则 -->
</template>
<style scoped>
.row {
  line-height: 38px;
}
.label-header {
  margin-left: 0;
  margin-right: 0;
  padding-left: 0;
  padding-right: 0;
}
.col-none {
  margin-left: 0;
  margin-right: 0;
  padding-left: 0;
  padding-right: 0;
}
.lable-middle {
  text-align: center;
}
</style>
<script>
import calendar from "../common/calendar.vue";
export default {
  props: ["toEditIds"],
  components: {
    calendar,
  },
  data() {
    return {
      companies: [],
      agentshow: false,
      selectCompany: [],
      selectCompanyName: "",
      allSelected: false,
      selectType: "",
      effectTime: "",
      premisesId: "",
      lostTimeState: false,
      state: "",
      parent: {},
      commission: {},
      listRules: [],
      amount: "",
      rate: "",
      commissionType: "",
      unit: "套",
      unitTitle: "",
      end1: "",
      rule1: "",
      start2: "",
      end2: "",
      rule2: "",
      start3: "",
      rule3: "",
      settlementCycle: "",
      isShow: false,
    };
  },
  watch: {
    toEditIds: {
      handler: function (val, oldVal) {
        this.initData();
      },
      //深层监听，当位对象时，若设为true，属性变更时即可触发，若为false，属性无法监听到
      deep: true,
    },
    state(curVal, oldVal) {
      //如果为失效，显示失效时间
      this.commission.lostTime = "";
      if (curVal == "0") {
        this.lostTimeState = true;
      } else {
        this.lostTimeState = false;
      }
    },
    commissionType(curVal, oldVal) {
      if (curVal == 1) {
        this.rate = "";
      } else if (curVal == 2) {
        this.amount = "";
      } else if (curVal == 3) {
        this.unit = "套";
        this.unitTitle = "套数";
      } else if (curVal == 4) {
        this.unit = "元";
        this.unitTitle = "金额";
      }
    },
  },
  mounted: function () {
    $("input[name=effecttime]").datetimepicker({
      format: "yyyy-mm-dd",
      autoclose: true,
      minView: 2,
      pickerPosition: "top-left",
      startDate: new Date(),
    });
    $("input[name=losttime]").datetimepicker({
      format: "yyyy-mm-dd",
      autoclose: true,
      minView: 2,
      startDate: new Date(),
    });
  },
  methods: {
    initData: function () {
      var _self = this;
      var url = _self.utilHelper.apiUrl + "/api/toUpdateCR";
      var body = {};
      body.params = this.toEditIds;
      _self.$http.post(url, body).then((response) => {
        if (response.body.result == "1") {
          //
          this.parent = response.body.resData.parent;
          this.commission = response.body.resData.commission;
          this.listRules = response.body.resData.listRules;
          this.initRules();
          this.commissionType = this.commission.commissionType;
          //有效时间初始化
          //                        $("#effecttime").val(_self.commission.effectTime);
          //                        $("#effecttime").text(_self.commission.effectTime);
          _self.commission.effectTime = this.utils.dateFormat(
            this.commission.effectTime,
            "yyyy-MM-dd"
          );
          $("#effecttime1").val(_self.commission.effectTime);
          if (this.commissionType == 1 || this.commissionType == 2) {
            this.selectType = true;
            this.mainType = "fixed";
            this.settlementCycle = this.commission.settlementCycle;
            if (this.commissionType == 1) {
              this.amount = this.commission.commissionAmmount;
              this.rate = "";
            } else {
              this.rate = this.commission.commissionRate;
              this.amount = "";
            }
          } else if (this.commissionType == 3 || this.commissionType == 4) {
            this.maintType = "labber";
            this.rate = null;
            this.amount = null;
            this.selectType = false;
            //规则补全
            for (var r in this.listRules) {
              if (this.listRules[r].order == "1") {
                this.end1 = this.listRules[r].end;
                this.rule1 = this.listRules[r].rule;
              } else if (this.listRules[r].order == "2") {
                this.start2 = this.listRules[r].start;
                this.end2 = this.listRules[r].end;
                this.rule2 = this.listRules[r].rule;
              } else if (this.listRules[r].order == "3") {
                this.start3 = this.listRules[r].start;
                this.rule3 = this.listRules[r].rule;
              }
            }
          }
          this.state = this.commission.state;
        }
      });
    },
    modelShow: function (name) {
      if (name == "#tab-fixed") {
        if (this.commissionType != 1 || this.commissionType != 1) {
          this.commissionType = 1;
        }
        this.selectType = true;
      } else if (name == "#tab-labber") {
        if (this.commissionType != 3 || this.commissionType != 4) {
          this.commissionType = 3;
        }
        this.selectType = false;
      }
    },
    editRule: function () {
      //参数校验
      var _self = this;
      _self.isShow = true;
      var rules = [];
      if (_self.state && _self.state == "0") {
        _self.commission.lostTime = $("#losttime").val();
        if (!_self.commission.lostTime) {
          layer.msg("请选择失效时间！", { icon: 5 });
          _self.isShow = false;
          return;
        }
      }
      if (!_self.commission.effectTime) {
        layer.msg("请选择生效时间！", { icon: 5 });
        _self.isShow = false;
        return;
      }
      if (!_self.state) {
        layer.msg("请选择分佣规则状态！", { icon: 5 });
        _self.isShow = false;
        return;
      }
      if (!_self.commissionType) {
        layer.msg("请选择分佣规则！", { icon: 5 });
        _self.isShow = false;
        return;
      }
      if (_self.selectType == true) {
        if (!_self.settlementCycle) {
          layer.msg("请选择佣金结算周期！", { icon: 5 });
          _self.isShow = false;
          return;
        }
        if (_self.commissionType != 1 && _self.commissionType != 2) {
          layer.msg("请选择分佣规则！", { icon: 5 });
          _self.isShow = false;
          return;
        }
        if (_self.commissionType == 1 && !_self.amount) {
          layer.msg("请至少填写一条佣金规则！", { icon: 5 });
          _self.isShow = false;
          return;
        }
        if (_self.commissionType == 2 && !_self.rate) {
          layer.msg("请至少填写一条佣金规则！", { icon: 5 });
          _self.isShow = false;
          return;
        }
      } else if (_self.selectType == false) {
        if (!_self.commission.settlementCycle) {
          layer.msg("请选择佣金结算周期！", { icon: 5 });
          _self.isShow = false;
          return;
        }
        if (_self.commissionType != 3 && _self.commissionType != 4) {
          layer.msg("请选择分佣规则！", { icon: 5 });
          _self.isShow = false;
          return;
        }
        if (_self.end1 && _self.start2) {
          if (parseFloat(_self.end1) >= parseFloat(_self.start2)) {
            layer.msg("填写规则不合法！", { icon: 5 });
            _self.isShow = false;
            return;
          }
        }

        if (_self.start2 && _self.end2) {
          if (parseFloat(_self.start2) >= parseFloat(_self.end2)) {
            layer.msg("填写规则不合法！", { icon: 5 });
            _self.isShow = false;
            return;
          }
        }

        if (_self.end2) {
          if (!_self.start2) {
            layer.msg("填写规则不合法！", { icon: 5 });
            _self.isShow = false;
            return;
          }
        }
        if (_self.end1 && _self.start3) {
          if (parseFloat(_self.end1) >= parseFloat(_self.start3)) {
            layer.msg("填写规则不合法！", { icon: 5 });
            _self.isShow = false;
            return;
          }
        }
        if (_self.end2 && _self.start3) {
          if (parseFloat(_self.end2) >= parseFloat(_self.start3)) {
            layer.msg("填写规则不合法！", { icon: 5 });
            _self.isShow = false;
            return;
          }
        }
        if (_self.end1) {
          rules.push({
            id: _self.commission.id,
            end: _self.end1,
            rule: _self.rule1,
            order: "1",
          });
        }
        if (_self.start2 && _self.end2) {
          rules.push({
            id: _self.commission.id,
            start: _self.start2,
            end: _self.end2,
            rule: _self.rule2,
            order: "2",
          });
        }
        if (_self.start3) {
          rules.push({
            id: _self.commission.id,
            start: _self.start3,
            rule: _self.rule3,
            order: "3",
          });
        }

        if (!(rules && rules.length > 0)) {
          layer.msg("请至少填写一条佣金规则！", { icon: 5 });
          _self.isShow = false;
          return;
        }
      }
      var params = {
        premisesId: _self.parent.premisesId,
        ruleString: JSON.stringify(rules),
        commissionType: _self.commissionType,
        commissionRate: _self.rate,
        commissionAmmount: _self.amount,
        effectTime: new Date($("#effecttime1").val()),
        state: _self.state,
        companyId: _self.parent.companyId,
        createUserId: _self.commission.createUserId,
        relationId: _self.commission.relationId,
        createTime: new Date(_self.commission.createTime),
        subRuleId: _self.commission.id,
        groupId: _self.commission.groupId,
      };
      if (_self.selectType == true) {
        params.settlementCycle = _self.settlementCycle;
      } else if (_self.selectType == false) {
        params.settlementCycle = _self.commission.settlementCycle;
      }
      if (_self.state == "0" && _self.commission.lostTime) {
        params.lostTime = new Date($("#losttime").val());
      }

      var url = _self.utilHelper.apiUrl + "/api/updateCR";
      var body = {};
      body.params = params;
      _self.$http.post(url, body).then((response) => {
        _self.isShow = false;
        if (response.body.result == "1") {
          $("#editRuleModal").modal("hide");
          layer.msg("更新成功！", { icon: 1 });
          //获取列表
          this.$parent.getCommissionRules();
        } else {
          layer.msg("更新失败！", { icon: 5 });
        }
      });
    },
    //规则清空
    initRules: function () {
      this.end1 = "";
      this.rule1 = "";
      this.start2 = "";
      this.end2 = "";
      this.rule2 = "";
      this.start3 = "";
      this.rule3 = "";
    },
    //验证输入合法性
    checkNum2Point: function (num, maxLength) {
      if (maxLength && num.length > maxLength) {
        layer.msg("最大长度为" + maxLength + "，保留两位小数！");
        return num.slice(0, maxLength);
      }
      if (/^\d+(\.\d{0,2})?$/.test(num)) {
        return num;
      } else if (num.length >= 1) {
        if (maxLength) {
          layer.msg("最大长度为" + maxLength + "，保留两位小数！");
        } else {
          layer.msg("保留两位小数！");
        }
        return num.substring(0, num.length - 1);
      }
    },
    checkNum: function (num, maxLength) {
      if (num.length > maxLength) {
        layer.msg("最大长度为" + maxLength);
        return num.slice(0, maxLength);
      }
      if (/^[0-9]+$/.test(num)) {
        return num;
      } else if (num.length >= 1) {
        layer.msg("请输入正整数！");
        return num.substring(0, num.length - 2);
      }
    },
  },
};
</script>
